package org.xxpay.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.entity.PayAlizftMchInfo;
import org.xxpay.core.entity.PayAlizftSettRecord;
import org.xxpay.core.entity.PayAlizftSettRecordExample;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.core.service.IPayAlizftMchInfoService;
import org.xxpay.core.service.IPayAlizftSettRecordService;
import org.xxpay.core.service.IPayOrderService;
import org.xxpay.service.dao.mapper.PayAlizftSettRecordMapper;

import java.util.List;

@Service
public class PayAlizftSettRecordServiceImpl implements IPayAlizftSettRecordService {

    @Autowired
    private PayAlizftSettRecordMapper payAlizftSettRecordMapper;

    @Autowired private IPayOrderService payOrderService;
    @Autowired private IPayAlizftMchInfoService payAlizftMchInfoService;

    @Override
    public int add(PayAlizftSettRecord payAlizftSettRecord) {
        return payAlizftSettRecordMapper.insertSelective(payAlizftSettRecord);
    }

    @Override
    public int update(PayAlizftSettRecord payAlizftSettRecord) {
        return payAlizftSettRecordMapper.updateByPrimaryKeySelective(payAlizftSettRecord);
    }

    @Override
    public int delete(Long id) {
        return payAlizftSettRecordMapper.deleteByPrimaryKey(id);
    }


    @Override
    public List<PayAlizftSettRecord> select(int offset, int limit, PayAlizftSettRecord payAlizftSettRecord) {
        PayAlizftSettRecordExample example = new PayAlizftSettRecordExample();
        example.setOrderByClause("CreateTime DESC");
        example.setOffset(offset);
        example.setLimit(limit);
        PayAlizftSettRecordExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, payAlizftSettRecord);
        return payAlizftSettRecordMapper.selectByExampleWithBLOBs(example);
    }

    @Override
    public long count(PayAlizftSettRecord payAlizftSettRecord) {
        PayAlizftSettRecordExample example = new PayAlizftSettRecordExample();
        PayAlizftSettRecordExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, payAlizftSettRecord);
        return payAlizftSettRecordMapper.countByExample(example);
    }

    @Override
    public PayAlizftSettRecord findById(Long subMchId) {
        return payAlizftSettRecordMapper.selectByPrimaryKey(subMchId);
    }

    @Override
    public int updateByCondition(PayAlizftSettRecord updateRecord, PayAlizftSettRecord condition, List<Byte> applyStatusList) {
        PayAlizftSettRecordExample example = new PayAlizftSettRecordExample();
        PayAlizftSettRecordExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, condition);

        if(applyStatusList !=null && !applyStatusList.isEmpty()){ //查询多个申请状态
            criteria.andStatusIn(applyStatusList);
        }

        return payAlizftSettRecordMapper.updateByExampleSelective(updateRecord, example);
    }

    @Override
    public Long initWaitRecord(String channelOrderNo, String payOrderId) {

        PayOrder payOrder = payOrderService.findByPayOrderId(payOrderId);
        if(payOrder == null){
            return null;
        }

        PayAlizftSettRecord record = new PayAlizftSettRecord();
        record.setPayOrderId(payOrderId);
        record.setPayOrderAmount(payOrder.getOrderAmount());
        record.setPayOrderSubject(payOrder.getSubject());
        record.setChannelOrderNo(channelOrderNo); // 支付宝订单号
        record.setSmid(payOrder.getChannelSMId()); //smid

        PayAlizftMchInfo subMchInfo = payAlizftMchInfoService.selectBaseInfoByPPAIdAndSmId(payOrder.getPassageAccountId(), payOrder.getChannelSMId());
        if(subMchInfo == null){ //空说明 二级商户数据已经删除， 不影响正常订单回调的结算。
            record.setSubMchId(-1L);
            record.setPassageTemplateId(-1L);
        }else{
            record.setSubMchId(subMchInfo.getSubMchId());
            record.setPassageTemplateId(subMchInfo.getPassageTemplateId());
            // 自动结算，直接返回null，由支付宝负责结算
            if(MchConstant.ALIZFT_SETT_TYPE_AUTO == subMchInfo.getSettType()) {
                return null;
            }
        }

        record.setStatus(MchConstant.ALIZFT_SETT_STATUS_NOT); //未结算状态
        payAlizftSettRecordMapper.insertSelective(record);

        return record.getId();
    }

    @Override
    public int updateWait2StatusAndCountAndMsg(PayAlizftSettRecord dbRecord, String thisApplyMsg, Byte updatedStatus) {

        PayAlizftSettRecord updateRecord = new PayAlizftSettRecord();
        updateRecord.setStatus(updatedStatus); //更新成功状态
        updateRecord.setRetryCount(dbRecord.getRetryCount() + 1); //累加次数， 暂不考虑并发问题
        updateRecord.appendApplyInfo(dbRecord.getApplyInfo(), thisApplyMsg);

        PayAlizftSettRecordExample example = new PayAlizftSettRecordExample();
        example.createCriteria().andIdEqualTo(dbRecord.getId()).andStatusEqualTo(MchConstant.ALIZFT_SETT_STATUS_NOT);

        return payAlizftSettRecordMapper.updateByExampleSelective(updateRecord, example);
    }

    void setCriteria(PayAlizftSettRecordExample.Criteria criteria, PayAlizftSettRecord payAlizftSettRecord) {
        if(payAlizftSettRecord != null) {
            if(StringUtils.isNotEmpty(payAlizftSettRecord.getSmid() )) criteria.andSmidEqualTo(payAlizftSettRecord.getSmid());
            if(payAlizftSettRecord.getStatus() != null && payAlizftSettRecord.getStatus() != -99) criteria.andStatusEqualTo(payAlizftSettRecord.getStatus());
            if(StringUtils.isNotEmpty(payAlizftSettRecord.getPayOrderId() )) criteria.andPayOrderIdEqualTo(payAlizftSettRecord.getPayOrderId());
            if(payAlizftSettRecord.getSubMchId() != null && payAlizftSettRecord.getSubMchId() != -99) criteria.andSubMchIdEqualTo(payAlizftSettRecord.getSubMchId());
            if(payAlizftSettRecord.getPassageTemplateId() != null) criteria.andPassageTemplateIdEqualTo(payAlizftSettRecord.getPassageTemplateId());
        }
    }
}
